package com.lw.leetcode.node;

/**
 * 1339. 分裂二叉树的最大乘积
 *
 * @Author liw
 * @Date 2021/5/21 11:47
 * @Version 1.0
 */
public class MaxProduct {

    public static void main(String[] args) {
        MaxProduct test = new MaxProduct();
        TreeNode instance = TreeNode.getInstance5();
        int i = test.maxProduct(instance);
        System.out.println(i);
    }

    int sum = 0;
    double min = 0D;

    public int maxProduct(TreeNode root) {
        getSum(root);
        double m = (double) sum / 2;
        min = m;
        find(root, m);
        long v = (long) (m + min);
        return (int) ((v * (sum - v)) % (1000000007));
    }

    private int find(TreeNode root, double m) {
        if (root == null) {
            return 0;
        }
        int l = find(root.left, m);
        if (l == -1) {
            return -1;
        } else if (l > m) {
            min = Math.min(min, l - m);
            return -1;
        }
        min = Math.min(min, m - l);
        if (min == 0D) {
            return -1;
        }
        int r = find(root.right, m);
        if (r == -1) {
            return r;
        } else if (r > m) {
            min = Math.min(min, r - m);
            return r;
        }
        min = Math.min(min, m - r);
        if (min == 0D) {
            return -1;
        }
        return root.val + l + r;
    }

    private void getSum(TreeNode root) {
        if (root == null) {
            return;
        }
        getSum(root.left);
        sum += root.val;
        getSum(root.right);
    }
}

